package com.example.jpa.service.impl;

import com.example.jpa.entity.User;
import com.example.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;


    @Override
    public User login(String username, String password) {
        return userRepository.findByUsernameAndPassword(username,password);
    }

    @Override
    public List<User> like(String username) {
        return userRepository.findByUsernameLike("%" + username + "%");
    }

    @Override
    public List<User> list(User user) {
        //构建查询匹配器，完成模糊查询
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //对username进行like模糊查询,contains包含查询
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                //排除password的查询
                .withIgnorePaths("password");
        //动态sql
        Example<User> userExample = Example.of(user,exampleMatcher);

        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //使用例子进行条件查询
        return userRepository.findAll(userExample,sort);
    }

    @Override
    public Page<User> page(User user, int pageSize, int pageNum) {
        //构建查询匹配器，完成模糊查询
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //对username进行like模糊查询,contains包含查询
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                //排除password的查询
                .withIgnorePaths("password");
        //动态sql
        Example<User> userExample = Example.of(user,exampleMatcher);

        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //构建分页
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize,sort);
        //使用例子进行条件查询
        return userRepository.findAll(userExample,pageRequest);
    }
}
